<?php

require_once PATH_FFWD.'core/baseobject.class.php';

class DatabaseField extends BaseObject{
	public $parent=NULL;
	
	public function __construct($name,$data=NULL,&$parent=NULL){
		parent::__construct(Array());
		$this->name=$name;
		$this->nq=-1;
		$this->parent=&$parent;
		foreach($data as $k=>$v)$this->$k=$v;
		if(isset($data['default']))$this->value=$data['default'];
	}
	
	public function isKey(){
		return $this->key;
	}
	
	public function setValue($v){	
		$err=$this->validate_value($v);
		if($err){
				return 0;
		};
		$this->value=$v;
	}
	
	public function isForeign(){
		return ($this->nq==-1?1:0);
	}
	
	public function unique(){
		$this->unique=1;
		if(!$this->isUnique()){
			$i=1;
			$v=$this->value;
			while(!$this->isUnique()){
				if($this->type=='varchar')
					$this->value=$v.'_'.(++$i);
				else
					$this->value=$v+($i++);
			}				
		}
	}
	
	public function isUnique(){
		//echo('DatabaseField::isUnique()<br/>');
		if(!$this->value || $this->value=='NULL')return 1;
		$pk=&$this->parent->getPrimaryKey();
		$query="SELECT * FROM `".$this->parent->getTableName()."` WHERE ".$this->query." = ".
					 "'".$this->value."' AND `".$pk->name."` != '".$pk->value."' ; ";
		$rs=$GLOBALS[$this->parent->database]->query($query);
		if($rs->num_rows){ 
			//if(DEBUG)echo "<br>".$this->name." is not unique (value:".$this->value.')<br/>';
			$this->parent->lasterror='value_not_unique';
			return 0;
		}else{
			return 1;
		}
	}
	
	public function validate_value(&$v){
		//if(DEBUG)console_log(''.$this->name.'->validate_value("'.$v.'");unique:'.$this->unique."\n");		
		//$this->value=$v;
		if($this->unique && !$this->isUnique())return 'value_not_unique';
		if(!$v)return 0;
		switch($this->type){
			case 'tinyint':
			case 'int':{
				if($v=='new')return 0;
				if(!is_numeric($v)){
					 $v=(int)$v;
					 return 'this_is_not_an_integer';
				}else{
					if(round($v)!=$v){
						$v=(int)$v;
					}
				}
				break;				
			}
			case 'float':{
				if(!is_numeric($v))return 'this_is_not_a_number';
				break;				
			}
			case 'timestamp':{
				if($v=='now()'){$this->nq=0;return 0;}else $this->nq=0;
				if(!$v){$v='';return 0;};
				//if(!preg_match('/^(19|20)[0-9]{2}(\.)(0[1-9]|1[012])(\.)(0[1-9]|1[0-9]|2[0-9]|3[0-1])(\.)([0-2][[0-9](\:)[0-5][0-9](\:)[0-5][0-9])/',$v))
				//	return 'this_is_not_a_date';
				if(preg_match('/([0-9]{4}).[\. \-]([0-9]{2}).[\. \-]([0-9]{2}).[\. \-]([0-9]{2})[:]([0-9]{2})[:]([0-9]{2})/',$v,$o)){
					array_shift($o);
					$v=implode('-',$o);
					$v[10]=' ';			
					$v[13]=':';
					$v[16]=':';
				}else return 'this is not a valid datetime';
				$v=strtotime($v);
				return 0;				
			}
			case 'date':{
				if($v=='now()'){$this->nq=0;return 0;}else $this->nq=1;
				if(!$v){$v='';return 0;};
				$v=strtodate($v);
				if(!preg_match('/^(19|20)[0-9]{2}(-)(0[1-9]|1[012])(-)(0[1-9]|1[0-9]|2[0-9]|3[0-1])/',$v))return 'this_is_not_a_date';
				break;				
			}
			case 'datetime':{
				if($v=='now()')return 0;
				if(!preg_match('/^(19|20)[0-9]{2}(-)(0[1-9]|1[012])(-)(0[1-9]|1[0-9]|2[0-9]|3[0-1])( )([0-9]|0[0-9]|1[0-9]|2[0-4])(:)([0-5][0-9])(:)([0-5][0-9])/',$v))return 'this_is_not_a_datetime';
				break;				
			}
			case 'varchar':{
				if($this->size && strlen($v)>$this->size)return 'value_too_long';
				return 0;
				break;				
			}
		};
		if(isset($this->validator))return $this->validator->validateValue($v);
		return 0;		
	} 
	
	public function validate(){
		$this->validate_value($this->value);		
	}
	
	public function __toString(){
		return (string)$this->value;		
	}
	
	public function input($p=Array()){
				
		if(!isset($p['readonly']))$p['readonly']=$this->readonly;
		if(!$p['readonly'])unset($p['readonly']);
		if(!isset($p['onchange']))$p['onchange']=$this->onchange;
		if(!isset($p['onclick']))$p['onclick']=$this->onclick;
		if($this->default && !$this->value){
			if((string)$this->parent->getPrimaryKey()=='new')$this->value=$this->default;
		}
				
		$p['uid']=$this->parent->getUID();
		if(!isset($p['name']))$p['name']=$this->name;
		if(!isset($p['value']))$p['value']=$this->value;
		if(!isset($p['placeholder']) && isset($p['pointer']))$p['placeholder']=$p['pointer'];
		//echo $p['uid'].': '.$p['pointer'].BR;
		if(isset($p['hidden']))return html_input_hidden($p);

		
		switch($this->type){
			case 'varchar':{
				if(isset($p['secure']) || $this->secure)return html_input_password($p);
				return html_input_varchar($p);					
			}
			default:{
				$f='html_input_'.$this->type;
				return $f($p);
			}
		}		
	}
	
	public function error(){
		$e=0;
		if(isset($_GET['error_'.$this->name])){
			$e=strtoupper($_GET['error_'.$this->name]);				
		}else{
			$e=$this->validate();	
		}
		if($e)return '<span class="errorstring">'.(translate($e)).'</span><br/>';
	}	
	
	public function getPointer(){
		if(is_array($this->join)){
			preg_match('/.*.`([a-zA-Z0-9_]+)`/',$this->query,$o);
			if(!count($o))return '';			
			return '['.$this->join['table'].']['.$this->parent->fields[$this->join['local']]->getPointer().']['.$o[1].']';
		}else
			return $this->parent->getPointer().'['.$this->name.']';		
	}
}